package com.mis.pos.controller;

import com.mis.pos.common.utils.ApiResponse;
import com.mis.pos.common.utils.HttpCode;
import com.mis.pos.entity.UserEntity;
import com.mis.pos.form.UserForm;
import com.mis.pos.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @description:
 * @author: yuxiang
 * @create: 2019-12-12 18:02
 **/
@RestController
@RequestMapping(value = "/user")
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;


    /**
     * 用户登录
     *
     * @param request
     * @param map
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/login")
    public ApiResponse login(HttpServletRequest request, @RequestBody Map<String, Object> map) throws Exception {

        ApiResponse response = new ApiResponse();
        logger.info("login开始...");
        // 登录失败从request中获取shiro处理的异常信息。
        // shiroLoginFailure:就是shiro异常类的全类名.
        String exception = (String) request.getAttribute("shiroLoginFailure");
        logger.info("exception=" + exception);
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken((String) map.get("username"), (String) map.get("password"));
            subject.login(token);
            String authorization = (String) subject.getSession().getId();
            response.setEvent(0);
            response.setObj(authorization); //将authorization传给前端，用于MySessionManager中请求的验证
            response.setMsg("登陆成功");
        } catch (IncorrectCredentialsException e) {
            response.setEvent(-1);
            response.setMsg("密码错误");
        } catch (LockedAccountException e) {
            response.setEvent(-1);
            response.setMsg("该用户已被禁用");
        } catch (AuthenticationException e) {
            response.setEvent(-1);
            response.setMsg("该用户不存在");
        }

        // 此方法不处理登录成功,由shiro进行处理
        return response;
    }

    /**
     * 按username账户从数据库中取出用户信息
     *
     * @param username 账户
     * @return
     */
    @GetMapping("/userList")
    @RequiresPermissions("user:view") // 权限管理.
    public UserEntity findUserInfoByUsername(@RequestParam String username) {
        return userService.findByUsername(username);
    }

    /**
     * 添加用户
     *
     * @param userEntity 用户实体，包含角色的相关信息
     * @return
     */
    @PostMapping("/userAdd")
    @RequiresPermissions("user:add")
    public ApiResponse addUser(@RequestBody UserEntity userEntity) {
        ApiResponse response = new ApiResponse();

        try {
            UserEntity temp = userService.addUser(userEntity);
            response.setMsg("添加用户成功");
            response.setObj(temp);
        } catch (Exception e) {
            e.printStackTrace();
            response.setEvent(-1);
            response.setMsg("服务器出现错误，添加用户失败");
        }
        return response;
    }

    @PostMapping("/userDel")
    @RequiresPermissions("user:del")
    public ApiResponse deleteUser(@RequestParam("userId") Long userId) {

        ApiResponse response = new ApiResponse();

        try {
            //1.查询用户是否存在
            UserEntity userEntity = userService.findById(userId);
            if (userEntity == null) {
                response.setEvent(-1);
                response.setMsg("用户不存在");
            }
            //2.删除用户
            if (userService.deleteUser(userEntity) == -1) {
                response.setEvent(-1);
                response.setMsg("数据库删除操作失败");
            }
            response.setEvent(0);
            response.setMsg("删除成功");

        } catch (Exception e) {
            e.printStackTrace();
            response.setEvent(-1);
            response.setMsg("服务器出现未知错误");
        }


        return response;
    }

    /**
     * 修改用户密码
     * @param userForm
     * @return
     */
    @PostMapping("changePass")
    public ApiResponse changeUser(@RequestBody UserForm userForm){
        ApiResponse apiResponse = new ApiResponse();
        try {
            if (StringUtils.isEmpty(userForm.getUsername())||StringUtils.isBlank(userForm.getUsername())){
                apiResponse.setEvent(-1);
                apiResponse.setMsg("用户名为空");
            }
            if (StringUtils.isEmpty(userForm.getOldPassword())||StringUtils.isBlank(userForm.getOldPassword())
                ||StringUtils.isEmpty(userForm.getNewPassword())||StringUtils.isBlank(userForm.getNewPassword())){
                apiResponse.setEvent(-1);
                apiResponse.setMsg("密码为空");
            }
            UserEntity userEntity  = userService.findByUsername(userForm.getUsername());
            if (userEntity!=null){
                if (userEntity.getPassword()!=userForm.getOldPassword()){
                    apiResponse.setEvent(-1);
                    apiResponse.setMsg("原密码不正确");
                }
                userEntity.setPassword(userForm.getNewPassword());
                addUser(userEntity);//添加用户
                apiResponse.setEvent(0);
                apiResponse.setMsg("修改密码成功");
            }


        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器错误");
        }
        return apiResponse;
    }
    /**
     * 注销
     *
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/logout")
    @RequiresPermissions("user:logout")
    public ApiResponse<String> logout(HttpServletRequest request) throws Exception {
        ApiResponse<String> resp = new ApiResponse<>();
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        resp.setEvent(0);
        resp.setMsg("注销成功");
        return resp;
    }

    /**
     * 未登录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/unauth")
    @ResponseBody
    public ApiResponse<String> unauth(HttpServletRequest request) throws Exception {
        ApiResponse<String> resp = new ApiResponse<>();
        resp.setEvent(HttpCode.Noauth);
        resp.setMsg("重新登录");
        return resp;
    }


    @RequestMapping(value = "/error")
    @ResponseBody
    public ApiResponse<String> error(HttpServletRequest request) throws Exception {
        ApiResponse<String> resp = new ApiResponse<>();
        resp.setEvent(-1);
        resp.setMsg("服务器异常");
        return resp;
    }
}
